package com.example.demo.leetcode.classics150;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _77求根节点到叶节点数字之和
 * @description
 * @date 2023/08/02 15:27
 * <p>
 * ******************************************************
 */
public class _77求根节点到叶节点数字之和 {

    int res = 0;

    public int sumNumbers(TreeNode root) {
        sum(root);
        return res;
    }

    private void sum(TreeNode root) {
        if (root == null) {
            return;
        }
        int val = root.val;
        if (root.left == null && root.right == null) {
            res += val;
            return;
        } else {
            if (root.left != null) {
                root.left.val += val * 10;
                sum(root.left);
            }
            if (root.right != null) {
                root.right.val += val * 10;
                sum(root.right);
            }
        }
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
